﻿using System.ComponentModel;

using VSTalk.Tools;

namespace VSTalk.Engine.ViewModel.ContactList
{

    public class ContactListViewModel : IListener, INotifyPropertyChanged
    {
        private TreeContactLayout _treeLayout;
        private PlotContactLayout _plotLayout;

        private IQuerySource _querySource;
        private ISubscription _layoutSwitcherUnit;

        public PlotContactLayout PlotLayout
        {
            get { return _plotLayout; }
        }

        public TreeContactLayout TreeLayout
        {
            get { return _treeLayout; }
        }

        public ContactListViewModel(IQuerySource querySource)
        {
            _querySource = querySource;

            _treeLayout = new TreeContactLayout();
            _plotLayout = new PlotContactLayout(querySource);

            AttemptToSetLayout();
        }

        private void AttemptToSetLayout()
        {
            if (string.IsNullOrEmpty(_querySource.SearchQuery))
            {
                _treeLayout.Activate();
                _plotLayout.Deactivate();
            }
            else
            {
                _treeLayout.Deactivate();
                _plotLayout.Activate();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void StartListen()
        {
            _treeLayout.StartListen();
            _plotLayout.StartListen();
            _layoutSwitcherUnit = _querySource.SubscribeToChange(() => _querySource.SearchQuery, _ => AttemptToSetLayout());
        }

        public void StopListen()
        {
            _layoutSwitcherUnit.Unsubscribe();
            _plotLayout.StopListen();
            _treeLayout.StopListen();
        }
    }
}